<template>
  <div>
    <el-form :inline="true" style="position: absolute;top: 100px;z-index: 50;left: 13px">
      <el-form-item>
        <el-select v-model="model">
          <el-option
            :label="$t('device')"
            value="device"
          />
          <el-option
            :label="$t('delete')"
            value="delete"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <el-row :gutter="1">
      <el-col :span="9">
        <div id="region_map" :style="{ height: device.deviceCore ? 'calc(100vh - 150px)':'calc(100vh - 85px)',width: '100%'}" />
        <div v-if="device.deviceCore" style=";width: 100%;background: #f3f3f1">
          <device-item
            :device="device"
          />
        </div>
      </el-col>
      <el-col :span="15">
        <div
          class="uni-scroll"
          style="height: calc(100vh - 100px);"
        >
          <sensor-camera-list :device="device" />
        </div>
      </el-col>
    </el-row>

    <el-dialog
      :visible.sync="dialogNameVisible"
    >
      <el-form>
        <el-form-item :label="$t('name')" label-width="20%">
          <el-input v-model="deviceBelongRegion.name" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogNameVisible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="insertDeviceBelongRegion">{{ $t('confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SensorCameraList from '@/components/SensorCameraList'
import DeviceItem from '@/components/DeviceItem/index'
import {
  listDeviceBelongRegion,
  insertDeviceBelongRegion,
  deleteDeviceBelongRegion
} from '@/api/iot/iotDeviceBelongRegionApi'
import { listDeviceBelongRegionDeviceDevice } from '@/api/iot/iotDeviceBelongRegionDeviceApi'
import { getCompanyId } from '@/util/storage'
import {
  formatDate,
  cancelNotice
} from '@/util/common'
export default {
  name: 'DeviceBelongRegion',
  components: {
    SensorCameraList,
    DeviceItem
  },
  data() {
    return {
      model: 'device',
      dialogNameVisible: false,
      deviceBelongRegion: {
        companyId: getCompanyId()
      },
      deviceBelongRegionList: [],
      map: {},
      markersArray: [],
      mapInfo: null,
      device: {}
    }
  }, mounted() {
    this.init()
    this.initData()
  },
  methods: {
    formatDate(time) {
      return formatDate(this, time)
    },
    initData() {
      const that = this
      listDeviceBelongRegion({
        companyId: this.deviceBelongRegion.companyId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.deviceBelongRegionList = data
          data.forEach(item => {
            const locs = item.pointList.split(',')
            const points = []
            for (let i = 0; i < locs.length - 1; i++) {
              const latLng = locs[i].split(' ')
              if (latLng) {
                points.push(
                  new window.qq.maps.LatLng(parseFloat(latLng[1]), parseFloat(latLng[0]))
                )
              }
            }
            const latLng = locs[0].split(' ')
            if (latLng) {
              const center = new window.qq.maps.LatLng(
                parseFloat(latLng[1]),
                parseFloat(latLng[0])
              )
              points.push(
                center
              )
              const marker = new window.qq.maps.Label({
                position: center,
                map: this.map,
                content: item.name,
                deviceBelongRegion: item
              })
              window.qq.maps.event.addListener(marker, 'click', function(e) {
                that.deviceBelongRegion = e.target.deviceBelongRegion
                switch (that.model) {
                  case 'device':
                    that.listDeviceBelongRegionDeviceDevice()
                    break
                  case 'delete':
                    that.deleteDeviceBelongRegion()
                    break
                  default:
                }
              })
            }
            new window.qq.maps.Polyline({
              path: points,
              map: this.map
            })
          })
        }
      })
    },
    deleteDeviceBelongRegion() {
      const that = this
      this.$confirm(this.$t('delete') + this.deviceBelongRegion.name, {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteDeviceBelongRegion({
            regionId: this.deviceBelongRegion.regionId
          }).then(() => {
            that.initData()
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    init() {

      this.map = new window.qq.maps.Map(document.getElementById('region_map'), {
        disableDefaultUI: true, // 禁止所有控件
        mapStyleId: 'style1'
      })
      this.mapInfo = new window.qq.maps.InfoWindow({
        map: this.map
      })
      const drawingManager = new window.qq.maps.drawing.DrawingManager({
        // drawingMode: window.qq.maps.drawing.OverlayType.MARKER,
        drawingControl: true,
        drawingControlOptions: {
          position: window.qq.maps.ControlPosition.TOP_CENTER,
          drawingModes: [
            window.qq.maps.drawing.OverlayType.POLYGON,
            window.qq.maps.drawing.OverlayType.RECTANGLE
          ]
        },
        markerOptions: {
          visible: false
        },
        circleOptions: {
          fillColor: new window.qq.maps.Color(255, 208, 70, 0.3),
          strokeColor: new window.qq.maps.Color(88, 88, 88, 1),
          strokeWeight: 3,
          clickable: false
        }
      })
      drawingManager.setMap(this.map)
      const overlaysArray = []
      const that = this
      window.qq.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
        if (event.type === 'marker') {
          that.clearOverlays(overlaysArray)
        } else if (event.type === 'polygon' || event.type === 'rectangle') {
          that.clearOverlays(overlaysArray)
          overlaysArray.push(event.overlay)
          let points = ''
          event.overlay.getPath().forEach(function(e) {
            const lng = e.getLng()
            const lat = e.getLat()
            points += lng + ' ' + lat + ','
          })
          console.log(points)
          that.deviceBelongRegion.pointList = points
          that.dialogNameVisible = true
        }
      })
    },
    clearOverlays(overlays) {
      let overlay
      while ((overlay = overlays.pop())) {
        overlay.setMap(null)
      }
    },
    showInfo(lng, lat, device, i) {
      const that = this
      const scaleSize = new window.qq.maps.Size(40, 40)
      const icon = new window.qq.maps.MarkerImage(
        device.iconUrl,
        null,
        null,
        null,
        scaleSize
      )
      const center = new window.qq.maps.LatLng(lat, lng)
      const marker = new window.qq.maps.Marker({
        position: center,
        map: this.map
      })
      marker.setIcon(icon)
      marker.ztn.device = device
      marker.center = center
      this.markersArray.push(marker)

      if (i === 0) {
        this.map.setCenter(marker.center)
        if (this.marker) {
          this.marker.setAnimation(null)
        }
        marker.setAnimation(window.qq.maps.MarkerAnimation.BOUNCE)
        this.marker = marker
        this.device = marker.ztn.device
      }
      // 获取标记的点击事件
      window.qq.maps.event.addListener(marker, 'click', function() {
        if (that.marker) {
          that.marker.setAnimation(null)
        }
        marker.setAnimation(window.qq.maps.MarkerAnimation.BOUNCE)
        that.marker = marker
        that.device = marker.ztn.device
      })
    },
    listDeviceBelongRegionDeviceDevice() {
      listDeviceBelongRegionDeviceDevice({
        regionId: this.deviceBelongRegion.regionId
      }).then(res => {
        const { data, code } = res
        if (code === '200') {
          this.total = data.total
          for (let i = 0; i < data.length; i++) {
            this.showInfo(data[i].lng, data[i].lat, data[i], i)
          }
          this.deviceList = data
        }
      })
    },
    insertDeviceBelongRegion() {
      insertDeviceBelongRegion({
        ...this.deviceBelongRegion
      }).then(() => {
        this.initData()
        this.dialogNameVisible = false
      })
    }
  }
}
</script>

<style scoped>

  .device-fun-button {
    font-size: 18px;
  }

</style>
